<template>
  <div class="jiaofk">
    <div class="cheleft">
      <el-form
        :model="ruleForm"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <div class="cheweiming">
          <p>缴费人员</p>
          <el-input
            placeholder="请输入缴费人员"
            v-model="ruleForm.username"
          ></el-input>
        </div>
        <div class="cheweiming">
          <p>缴费名称:</p>
          <el-input
            placeholder="请输入缴费名称"
            v-model="ruleForm.payname"
          ></el-input>
        </div>
        <div class="cheweiming">
          <p>支付类型:</p>
          <el-select
            class="cheleixing"
            v-model="ruleForm.costtype"
            placeholder="输入支付类型"
          >
            <el-option label="支付宝支付" :value="1"></el-option>
            <el-option label="微信支付" :value="2"></el-option>
            <el-option label="银联支付" :value="3"></el-option>
          </el-select>
        </div>
        <div class="cheweiming">
          <p>支付状态:</p>
          <el-select
            class="cheleixing"
            v-model="ruleForm.coststatus"
            placeholder="选择支付状态"
          >
            <el-option label="已支付" :value="1"></el-option>
            <el-option label="未支付" :value="2"></el-option>
          </el-select>
        </div>
        <div class="cheweiming">
          <p class="demonstration">支付时间</p>
          <div class="block">
            <el-date-picker
              class="cheleixing"
              v-model="value1"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
            >
            </el-date-picker>
          </div>
        </div>
        <div class="cheweiming">
          <p>缴费金额:</p>
          <el-input
            placeholder="输入缴费金额"
            v-model="ruleForm.paymoney"
          ></el-input>
        </div>
        <div class="cheweiming" v-if="open">
          <p>缴费优先级:</p>
          <el-input
            placeholder="缴费优先级"
            v-model="ruleForm.paylevel"
          ></el-input>
        </div>
        <div class="dakai" @click="open = !open">
          <i :class="open ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i
          >{{ open ? "收起" : "打开" }}
        </div>
        <div class="anniuk">
          <el-button @click="chongzhi" class="chong">重置</el-button>
          <el-button @click="cha" class="chong" type="primary"
            >立即查询</el-button
          >
        </div>
      </el-form>
    </div>
    <div class="jiaoright">
      <div class="you-top">
        <h2>缴费列表</h2>
        <el-button @click="exportCurrentPage" class="daochu" type="primary"
          ><i class="el-icon-download"></i>导出</el-button
        >
      </div>
      <div>
        <el-table 
          id="costTable"
          :data="tableData" 
          border 
          stripe 
          style="width: 100%"
          :loading="loading"
        >
          <el-table-column prop="payname" label="续费产品">
            <template slot-scope="scope">
              {{ scope.row.payname || "暂无" }}
            </template>
          </el-table-column>
          <el-table-column prop="username" label="缴费人员">
            <template slot-scope="scope">
              {{ scope.row.username || "暂无" }}
            </template>
          </el-table-column>
          <el-table-column prop="costtype" label="支付类型">
            <template slot-scope="scope">
              {{
                { 1: "支付宝支付", 2: "微信支付", 3: "银联支付" }[
                  scope.row.costtype
                ] || "暂无"
              }}
            </template>
          </el-table-column>
          <el-table-column prop="paymoney" label="缴费金额">
            <template slot-scope="scope">
              {{ scope.row.paymoney || "暂无" }}
            </template>
          </el-table-column>
          <el-table-column prop="paylevel" label="缴费优先级">
            <template slot-scope="scope">
              {{ scope.row.paylevel || "暂无" }}
            </template>
          </el-table-column>
          <el-table-column prop="paytime" label="支付时间">
            <template slot-scope="scope">
              {{ formatDateTime(scope.row.paytime) || "暂无" }}
            </template>
          </el-table-column>
          <el-table-column prop="coststatus" label="支付状态">
            <template slot-scope="scope">
              {{ scope.row.coststatus == 1 ? "已支付" : "未支付" }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="220px">
            <template slot-scope="scope">
              <el-button
                size="mini"
                class="jiaochakan"
                @click="handleEdit(scope.$index, scope.row)"
                >查看</el-button
              >
              <!-- 单条导出按钮，绑定handleDerive方法并传递当前行数据 -->
              <el-button
                size="mini"
                @click="handleDerive(scope.row)"
                >导出</el-button
              >
              <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <div class="block fenye">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currPage"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="pageNum"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as XLSX from 'xlsx';
import FileSaver from 'file-saver';

export default {
  data() {
    return {
      open: false,
      ruleForm: {
        username: "",
        payname: "",
        costtype: "",
        coststatus: "",
        startDate: "",
        endDate: "",
        paymoney: "",
        paylevel: "",
        token: "",
      },
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      value1: "",
      value2: "",
      currPage: 1,
      pageNum: 10,
      tableData: [],
      total: 0,
      loading: false,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 1. 导出单条数据
    handleDerive(row) {
      if (!row) {
        this.$message.warning("数据不存在，无法导出");
        return;
      }

      this.$confirm(`是否导出【${row.username}-${row.payname}】的缴费数据?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        try {
          // 定义表头（与表格列对应）
          const headers = [
            "续费产品", 
            "缴费人员", 
            "支付类型", 
            "缴费金额", 
            "缴费优先级", 
            "支付时间", 
            "支付状态"
          ];

          // 处理单条数据（格式化数字类型为文字）
          const rowData = [
            row.payname || "暂无",
            row.username || "暂无",
            { 1: "支付宝支付", 2: "微信支付", 3: "银联支付" }[row.costtype] || "暂无",
            row.paymoney || "暂无",
            row.paylevel || "暂无",
            this.formatDateTime(row.paytime) || "暂无",
            row.coststatus === 1 ? "已支付" : "未支付"
          ];

          // 创建工作表和工作簿
          const worksheet = XLSX.utils.aoa_to_sheet([headers, rowData]);
          const workbook = XLSX.utils.book_new();
          XLSX.utils.book_append_sheet(workbook, worksheet, "缴费详情");

          // 生成文件名（含唯一标识，避免重复）
          const timeStamp = new Date().toISOString().replace(/[:.-]/g, "");
          const fileName = `缴费数据_${row.username}_${row.payname}_${timeStamp}.xlsx`;

          // 导出文件
          XLSX.writeFile(workbook, fileName);
          this.$message.success("单条数据导出成功");
        } catch (error) {
          this.$message.error("导出失败，请重试");
          console.error("单条导出错误:", error);
        }
      }).catch(() => {
        this.$message.info("已取消导出");
      });
    },

    exportCurrentPage() {
      this.$confirm("是否确认导出当前页缴费数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        try {
          const tableDom = document.querySelector("#costTable");
          if (!tableDom) {
            this.$message.error("未找到表格，导出失败");
            return;
          }

          const wb = XLSX.utils.table_to_book(tableDom);
          const wbout = XLSX.write(wb, {
            bookType: "xlsx",
            bookSST: true,
            type: "array",
          });

          const currentTime = new Date().toISOString().replace(/[:.-]/g, "");
          const fileName = `缴费数据_第${this.currPage}页_${currentTime}.xlsx`;
          FileSaver.saveAs(
            new Blob([wbout], { type: "application/octet-stream" }),
            fileName
          );

          this.$message.success("当前页数据导出成功");
        } catch (e) {
          this.$message.error("导出失败，请重试");
          console.error("当前页导出错误:", e);
        }
      }).catch(() => {
        this.$message.info("已取消当前页导出");
      });
    },

    // 以下为原有方法（未修改）
    chongzhi() {
      this.ruleForm.payname = "";
      this.ruleForm.username = "";
      this.ruleForm.costtype = "";
      this.value1 = "";
      this.ruleForm.coststatus = "";
      this.ruleForm.paymoney = "";
      this.ruleForm.paylevel = "";
      this.getList();
    },
    cha() {
      this.getcha();
    },
    async getcha() {
      const tit = {
        payname: this.ruleForm.payname || "",
        username: this.ruleForm.username || "",
        costtype: this.ruleForm.costtype || "",
        coststatus: this.ruleForm.coststatus || "",
        startDate: this.value1 ? this.value1[0] : "",
        endDate: this.value1 ? this.value1[1] : "",
        paymoney: this.ruleForm.paymoney || "",
        paylevel: this.ruleForm.paylevel || "",
        currPage: this.currPage - 1,
        pageNum: this.pageNum,
      };
      let res = await this.$axios.get(
        `http://community.byesame.com/cost/getPayMessage`,
        { params: tit }
      );
      console.log("查询成功", res);
      this.$message({
        type: "success",
        message: "查询成功",
      });
      this.tableData = res.data.data;
      this.total = res.data.total;
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageNum = val;
      this.getList();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currPage = val;
      this.getList();
    },
    handleEdit(index, row) {
      console.log(index, row);
      this.$router.push({
        path: "/pay/jiaoxiang",
        query: { id: row.id },
      });
    },
    handleDelete(index, row) {
      console.log(index, row);
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.getdel(row.id);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    async getdel(id) {
      let res = await this.$axios.get(
        `http://community.byesame.com/cost/delCostData?id=${id}&token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJhZG1pbiIsImVtYWlsIjoiMjQ1MzMxNzM1N0BxcS5jb20iLCJoZWFkIjoiMS5qcGciLCJ0eXBlIjoiMSIsImlhdCI6MTc2MTcwMzk5MCwiZXhwIjoxNzYxNzkwMzkwfQ.unh5Img4da9DjodLV1c4cCXdrSvkFwAIadW7MGeQYhA`
      );
      console.log("删除成功", res);
      this.getList();
    },
    async getList() {
      let res = await this.$axios.get(
        `http://community.byesame.com/cost/getPayMessage?currPage=${
          this.currPage - 1
        }&pageNum=${this.pageNum}`
      );
      console.log(res);
      this.tableData = res.data.data;
      this.total = res.data.total;
    },
    formatDateTime(isoTime) {
      if (!isoTime) return "";
      const date = new Date(isoTime);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      const hours = String(date.getHours()).padStart(2, "0");
      const minutes = String(date.getMinutes()).padStart(2, "0");
      const seconds = String(date.getSeconds()).padStart(2, "0");
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
  },
};
</script>

<style scoped>
.jiaofk {
  display: flex;
  justify-content: space-between;
}
.cheleft {
  width: 25%;
}
.cheweiming p {
  margin-bottom: 0.625rem;
  margin-top: 0.625rem;
}
.cheleixing {
  width: 25.625rem;
}
.dakai {
  width: 25.625rem;
  text-align: center;
  margin: 1.25rem 0;
}
.anniuk {
  display: flex;
  justify-content: space-around;
}
.chong {
  padding: 0.625rem 3.125rem;
  margin: 0 1.875rem;
}
.jiaoright {
  width: 73%;
}
.you-top {
  margin-top: 1.875rem;
  margin-bottom: 1.875rem;
  display: flex;
  justify-content: space-between;
  gap: 10px; /* 增加按钮间距 */
}
.daochu {
  padding: 0.5625rem 0.75rem;
  margin-right: 1.25rem;
}
.fenye {
  float: right;
  margin: 1.25rem;
}
</style>